<?php
class Event_StaticPageVersionForm extends Crud_Event_Handler
{
	protected $_type = 'form';

	/**
	 * Run handler with options array.
	 *
	 * @param Crud_Form $form
	 * @return void
	 */
	public function run($form)
	{
		//подменяем данные из истории
		$row = $form->getRow();
		if ($row instanceof Crud_Section_Row) {
			$staticPageRow = $row->getRow();
		}
		
		if (empty($staticPageRow)) {
			$staticPageRow = StaticPagePeer::getInstance()->createRow();
		}
		
		/* @var $staticPageRow StaticPageRow */
		$staticPageVersionRow = PagesService::getInstance()->getLastPageVersion($staticPageRow);
		if ($staticPageVersionRow instanceof StaticPageVersionRow) {
			
			$columns = PagesService::$versionFields;
			$flips = array_flip($columns);
			//исключаем пока эти поля
			
			foreach ($columns as $column) {
				$field = StaticPagePeer::tableFieldNameToClassField($column);
				$element = $form->getElement($column);
				$element->setValue($staticPageVersionRow->{'get'.$field}());
			}
		} else {
			$staticPageVersionRow = StaticPageVersionPeer::getInstance()->createRow();
		}
		
		$element = new Zend_Form_Element_Checkbox('admin_user_is_approved_version');
		if (0 < $staticPageRow->getId() && PagesService::getInstance()->checkApprovePageByAdminUser($staticPageRow)) {
			//формирование флага для апрува.
			$element->setLabel('Утвердить?');
		
			
			if (!$staticPageVersionRow->getIsApprovedVersion()) {
				/* @var $approvedRow StaticPageVersionApproveRow */
				$approvedRow = PagesService::getInstance()->getApprovePageRow($staticPageVersionRow);
				if ($approvedRow instanceof StaticPageVersionApproveRow) {
					$element->setValue($approvedRow->getIsApproved());
				}
			}
			$form->addElement($element);
		}
		
		$approvedRowset = PagesService::getInstance()->getAllApprovedByAdminUser($staticPageVersionRow);
		$userList = PagesService::getInstance()->getApproverUserList($staticPageRow);
		
		if (!$staticPageVersionRow->getIsApprovedVersion() && ($element->getValue() == 1 
			|| ($userList->count() != 0 && $userList->count() <= $approvedRowset->count()))) {
			/* @var $element Zend_Form */
			foreach ($form->getElements() as $element) {
				$arr = explode(' ', $element->getAttrib('class'));
				$element->setAttrib('class', implode(' ', array_diff($arr, array('wysiwyg'))));
				
				$element->setAttrib('disabled', 'disabled');
				$element->setAttrib('readonly', true);
			}
		}
		
		
		//вывод данных через кастомную форму
		$decoratorScript = new Zend_Form_Decorator_ViewScript();
		$decoratorScript->setViewScript('static-page-version/form.phtml');
	    $form->setDecorators(array(
	        new Zend_Form_Decorator_PrepareElements(),
	    	$decoratorScript,
	    ));
		
	}
}